package com.gqj.meter.controller;

import com.gqj.common.annotation.Log;
import com.gqj.common.constant.BusinessConstants;
import com.gqj.common.core.controller.BaseController;
import com.gqj.common.core.domain.AjaxResult;
import com.gqj.common.core.page.TableDataInfo;
import com.gqj.common.enums.BusinessType;
import com.gqj.common.exception.ServiceException;
import com.gqj.common.utils.DateUtils;
import com.gqj.common.utils.StringUtils;
import com.gqj.common.utils.poi.ExcelUtil;
import com.gqj.meter.domain.MdInTask;
import com.gqj.meter.domain.MdInTaskDetails;
import com.gqj.meter.domain.MdOutTaskDetails;
import com.gqj.meter.domain.vo.MdInTaskDetailsVo;
import com.gqj.meter.domain.vo.MdOutTaskDetailsVo;
import com.gqj.meter.mapper.MdInTaskMapper;
import com.gqj.meter.service.IMdInTaskDetailsService;
import com.gqj.meter.service.IMdInTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 入库明细Controller
 *
 * @author lxq
 * @date lxq-02-10
 */
@Api(value = "/meter/mdInTaskDetails", description = "入库明细")
@RestController
@RequestMapping("/meter/mdInTaskDetails")
public class MdInTaskDetailsController extends BaseController {
    @Autowired
    private IMdInTaskDetailsService mdInTaskDetailsService;
    @Autowired
    private IMdInTaskService mdInTaskService;
    @Autowired
    private MdInTaskMapper mdInTaskMapper;

    /**
     * 查询出入库明细列表
     */
    @ApiOperation("查询入库明细列表")
    @PreAuthorize("@ss.hasPermi('meter:mdInTaskDetails:list')")
    @GetMapping("/list")
    public TableDataInfo list(MdInTaskDetails mdInTaskDetails) {
        startPage();
        List<MdInTaskDetails> list = mdInTaskDetailsService.selectMdInTaskDetailsList(mdInTaskDetails);
        return getDataTable(list);
    }

    /**
     * 导出入库明细列表
     */
    @PreAuthorize("@ss.hasPermi('meter:mdInTaskDetails:export')")
    @ApiOperation("导出入库明细")
    @Log(title = "入库明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MdInTaskDetails mdInTaskDetails) {
        //根据单号查询单据类型
       List<MdInTask> listTask = mdInTaskService.selectMdInTaskList(new MdInTask(){{setInTaskNo(
               mdInTaskDetails.getInTaskNo());}});
       if(listTask.size() < 0){
           throw new ServiceException("单据不存在");
       }

        List<MdInTaskDetails> list = mdInTaskDetailsService.exportMdInTaskDetailsListExcel(mdInTaskDetails);
        List<MdInTaskDetailsVo> listvo = new ArrayList<>();
        int i=0;
        for (MdInTaskDetails mdInTaskDetails1 : list) {
            i++;
            MdInTaskDetailsVo mdInTaskDetailsVo = new MdInTaskDetailsVo();
            mdInTaskDetailsVo.setNum(i);
            mdInTaskDetailsVo.setTypeCode(mdInTaskDetails1.getTypeCode());
            mdInTaskDetailsVo.setRfidNo(mdInTaskDetails1.getRfidNo());
            mdInTaskDetailsVo.getRemark();
            listvo.add(mdInTaskDetailsVo);
        }
        MdInTaskDetailsVo mdInTaskDetailsVo = new MdInTaskDetailsVo();
        mdInTaskDetailsVo.setNum(null);
        mdInTaskDetailsVo.setTypeCode("配送单位");
        mdInTaskDetailsVo.setRfidNo("岩泉供电所");
        mdInTaskDetailsVo.setRemark("日期："+ DateUtils.getDate().replaceAll("-","."));

        listvo.add(mdInTaskDetailsVo);

        ExcelUtil<MdInTaskDetailsVo> util = new ExcelUtil<MdInTaskDetailsVo>(MdInTaskDetailsVo.class);
        //查询单据类型
        String taskOrderType =listTask.get(0).getTaskOrderType();
        if (taskOrderType.equals(BusinessConstants.TASK_ORDER_TYPE_RETURN)) {
            util.exportExcel(response, listvo, "入库明细数据","拆回电能表交接清单");
        }else {
            util.exportExcel(response, listvo, "入库明细数据","电能表交接清单");
        }
    }

    @PostMapping("/importTemplate")
    @PreAuthorize("@ss.hasPermi('meter:mdInTaskDetails:importTemplate')")
    @ApiOperation("下载入库单明细导入模板")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<MdInTaskDetails> util = new ExcelUtil<MdInTaskDetails>(MdInTaskDetails.class);
        util.importTemplateExcel(response, "入库明细导入模板");
    }

    @Log(title = "入库单明细导入", businessType = BusinessType.IMPORT)
    @ApiOperation("入库单明细导入")
    @PreAuthorize("@ss.hasPermi('meter:mdInTaskDetails:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, String inTaskNo, Boolean isCoverSupport) throws Exception {

        ExcelUtil<MdInTaskDetails> util = new ExcelUtil<MdInTaskDetails>(MdInTaskDetails.class);
        List<MdInTaskDetails> inTaskDetailsList = util.importExcel(file.getInputStream());
        if (StringUtils.isEmpty(inTaskDetailsList)) {
            return AjaxResult.error("导入明细数据不能为空！");
        }

        if (StringUtils.isNull(inTaskNo)) {
            return AjaxResult.error("任务编号为空，请联系系统管理员");
        }
        if (StringUtils.isNull(isCoverSupport)) {
            return AjaxResult.error("是否覆盖为空，请联系系统管理员");
        }

        MdInTask mdInTask = mdInTaskMapper.selectMdInTaskByInTaskNo(inTaskNo);
        if (StringUtils.isNull(mdInTask)) {
            return AjaxResult.error("导入'" + inTaskNo + "'任务明细失败，任务编号不存在");
        }
        if (!"0".equals(mdInTask.getStatusCode())) {
            return AjaxResult.error("任务单据'" + mdInTask.getInTaskNo() + "'不是待执行状态，无法导入");
        }

        String massge = mdInTaskDetailsService.importMdInTaskDetails(inTaskDetailsList, inTaskNo, mdInTask.getAssetsCategory(), isCoverSupport);
        return AjaxResult.success(massge);
    }

    /**
     * 获取入库明细详细信息
     */
    @ApiOperation("获取入库明细详细信息")
    @PreAuthorize("@ss.hasPermi('meter:mdInTaskDetails:query')")
    @GetMapping(value = "/{inTaskDetailsId}")
    public AjaxResult getInfo(@PathVariable("inTaskDetailsId") Long inTaskDetailsId) {
        return success(mdInTaskDetailsService.selectMdInTaskDetailsByInTaskDetailsId(inTaskDetailsId));
    }

    /**
     * 新增出入库明细
     */
    @ApiOperation("新增入库明细")
    @PreAuthorize("@ss.hasPermi('meter:mdInTaskDetails:add')")
    @Log(title = "入库明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody List<MdInTaskDetails> mdInTaskDetailsList) {
        if (StringUtils.isNull(mdInTaskDetailsList)) {
            return AjaxResult.error("明细为空，请检查重试！");
        }

        return toAjax(mdInTaskDetailsService.insertMdInTaskDetails(mdInTaskDetailsList));
    }

    /**
     * 修改出入库明细
     */
    @ApiOperation("修改入库明细")
    @PreAuthorize("@ss.hasPermi('meter:mdInTaskDetails:edit')")
    @Log(title = "入库明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MdInTaskMap mdInTaskMap) throws IOException, ParserConfigurationException, SAXException {
        Long inTaskId = mdInTaskMap.getInTaskId();
        if (null == inTaskId || inTaskId == 0) {
            return AjaxResult.error("任务ID为空，请联系系统管理员！");
        }

        String inTaskNo = mdInTaskMap.getInTaskNo();
        if (null == inTaskNo || "".equals(inTaskNo)) {
            return AjaxResult.error("任务编号为空，请联系系统管理员！");
        }

        String assetsCategory = mdInTaskMap.getAssetsCategory();
        if (null == assetsCategory || "".equals(assetsCategory)) {
            return AjaxResult.error("资产大类为空，请联系系统管理员！");
        }

        MdInTask mdInTask = mdInTaskService.selectMdInTaskByInTaskId(inTaskId);
        if (null == mdInTask) {
            return AjaxResult.error("任务不存在，请联系系统管理员！");
        }
        if (!inTaskNo.equals(mdInTask.getInTaskNo())) {
            return AjaxResult.error("任务编号不匹配，请联系系统管理员！");
        }
        if (!assetsCategory.equals(mdInTask.getAssetsCategory())) {
            return AjaxResult.error("资产大类不匹配，请联系系统管理员！");
        }
        if (!"1".equals(mdInTask.getStatusCode())) {
            return AjaxResult.error("任务不是执行中状态，无法修改明细！");
        }

        List<MdInTaskDetails> mdInTaskDetailsList = mdInTaskMap.getMdInTaskDetailsList();
        if (null == mdInTaskDetailsList || mdInTaskDetailsList.size() == 0) {
            return AjaxResult.error("任务明细为空，请联系系统管理员！");
        }
        mdInTaskMap.setTaskOrderType(mdInTask.getTaskOrderType());
        mdInTaskMap.setOperId(mdInTask.getOperId());
        mdInTaskMap.setRelaId(mdInTask.getRelaId());
        return toAjax(mdInTaskDetailsService.updateMdInTaskDetails(mdInTaskMap));
    }

    public static class MdInTaskMap {
        /**
         * 主键
         */
        private Long inTaskId;

        private String assetsCategory;

        private String inTaskNo;

        private String taskOrderType;

        private Long operId;

        private String useEquipment;

        private Long relaId;

        public Long getRelaId() {
            return relaId;
        }

        public void setRelaId(Long relaId) {
            this.relaId = relaId;
        }

        public String getUseEquipment() {
            return useEquipment;
        }

        public void setUseEquipment(String useEquipment) {
            this.useEquipment = useEquipment;
        }

        public Long getOperId() {
            return operId;
        }

        public void setOperId(Long operId) {
            this.operId = operId;
        }

        private List<MdInTaskDetails> mdInTaskDetailsList;

        public String getTaskOrderType() {
            return taskOrderType;
        }

        public void setTaskOrderType(String taskOrderType) {
            this.taskOrderType = taskOrderType;
        }

        public String getAssetsCategory() {
            return assetsCategory;
        }

        public void setAssetsCategory(String assetsCategory) {
            this.assetsCategory = assetsCategory;
        }

        public String getInTaskNo() {
            return inTaskNo;
        }

        public void setInTaskNo(String inTaskNo) {
            this.inTaskNo = inTaskNo;
        }

        public Long getInTaskId() {
            return inTaskId;
        }

        public void setInTaskId(Long inTaskId) {
            this.inTaskId = inTaskId;
        }

        public List<MdInTaskDetails> getMdInTaskDetailsList() {
            return mdInTaskDetailsList;
        }

        public void setMdInTaskDetailsList(List<MdInTaskDetails> mdInTaskDetailsList) {
            this.mdInTaskDetailsList = mdInTaskDetailsList;
        }
    }

    /**
     * 删除出入库明细
     */
    @ApiOperation("删除入库明细")
    @PreAuthorize("@ss.hasPermi('meter:mdInTaskDetails:remove')")
    @Log(title = "入库明细", businessType = BusinessType.DELETE)
    @DeleteMapping("/{inTaskDetailsIds}/{inTaskNo}")
    public AjaxResult remove(@PathVariable Long[] inTaskDetailsIds, @PathVariable String inTaskNo) {
        if (StringUtils.isNull(inTaskNo)) {
            return AjaxResult.error("任务编号为空，请联系系统管理员！");
        }
        MdInTask mdInTask = mdInTaskMapper.selectMdInTaskByInTaskNo(inTaskNo);
        if (!"0".equals(mdInTask.getStatusCode())) {
            return AjaxResult.error("任务已执行，不允许删除明细！");
        }
        return toAjax(mdInTaskDetailsService.deleteMdInTaskDetailsByInTaskDetailsIds(inTaskDetailsIds));
    }


    @ApiOperation("获取设备利用率数据")
    @PreAuthorize("@ss.hasPermi('meter:mdInTaskDetails:getEquipmentUseData')")
    @PostMapping("/getEquipmentUseData")
    public AjaxResult getEquipmentUseData() {
        return success(mdInTaskDetailsService.getTaskDetailsEquipment());
    }

}
